import React, { useEffect, useState } from 'react';
import {Button, message, Modal, Spin, Upload, UploadProps } from 'antd';
import styles from './index.less';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { EyeOutlined, LoadingOutlined } from '@ant-design/icons';
import PermissionManage from '@/components/PermissionManage';
import FileUpload from '@/components/FileUpload';
import { getExcelList } from '@/services/public';

const antIcon = <LoadingOutlined  style={{ fontSize: 16 }} spin />

const UploadFileList: React.FC<any> = ({
    onChange,
}) => {
    
    const [visible, setVisible] = useState<any>(false);
    const [tableList, setTableList] = useState<any>([]);
    const [uploadType, setUploadType] = useState<any>('');
    const [publicContent, setPublicContent] = useState<any>('');
    const [contentVisible, setContentVisible] = useState<any>(false);
    const [uploadloading, setUploadloading] = useState<boolean>(false);
    const [info, setInfo] = useState<any>({});

    const handleSubmit = () => {
        let listJson = JSON.stringify(tableList)
        onChange(listJson)
        setVisible(false)
        setUploadType('')
        setInfo({})
    }

    const handleExcelUpload = async(value:any) => {
        let res = await getExcelList({
            descriptionOfBranchAccessFile:value[0].fileId
        })
        if (res && res.success) {
            setTableList(res.data)
            setVisible(true)
        }else{
            message.error(res.errMsg)
        }
    }

    const handleTableList = (data:any,info:any,type:string) => {
        setTableList((list:any)=>{
            const newList = list.map((item:any)=>{
                if (item.id == info.id) {
                    item[type] = data.fileId,
                    item[type+'Url'] = data.url
                }
                return item
            })
            return newList
        })
    }

    const handleUploadChange = ({ fileList: newFileList = [], file = {} }:any, info:any, type:string) => {
        //如果没有status，认为被beforeUpload拦截
        if (!file.status) {
          return;
        }
        setUploadType(type)
        setInfo(info)
        setUploadloading(true)
        if (file.status == 'done') {
          const response = file.response;
          if (response && response.success) {
              handleTableList(response.data, info, type)
          } else {
            file.status = 'error';
            file.name = response.errMsg || '上传失败';
            message.error(response.errMsg || '系统超时，请刷新重试！');
          }
          setUploadloading(false)
        }
    }

    const handleModalCancel = () => {
        setVisible(false)
        setUploadType('')
        setInfo({})

    }

    const props: UploadProps = {
        name: 'file',
        showUploadList:false,
        action: '/open/upload/resource',
        maxCount:1,
        data:{
          ossEnum:'BANK'
        },
    };

    const columns: ProColumns<any>[] = [
        {
            title: '银行名称',
            dataIndex: 'branchName',
        },
        {
            title: '地区',
            dataIndex: 'district',
        },
        {
            title: '申请人',
            dataIndex: 'name',
        },
        {
            title: '申请人电话',
            dataIndex: 'phone',
        },
        {
            title: '营业执照',
            dataIndex: 'businessLicense',
            render:(text,record)=>{
                return <div className={styles.uploadAction}>
                    {
                        record.businessLicenseUrl ? 
                        <a onClick={()=>{
                            setPublicContent(record.businessLicenseUrl)
                            setContentVisible(true)
                          }} ><EyeOutlined /> </a>
                        :null

                    }
                    <Spin  style={{display:'inline-block'}} indicator={antIcon} spinning={uploadloading&&uploadType == 'businessLicense'&&record.id == info.id}>
                        <Upload  {...props} onChange={(file)=>{handleUploadChange(file,record,'businessLicense')}} >
                            <a style={{whiteSpace:'nowrap'}}>{record.businessLicense ? '重新上传':'上传'}</a>
                        </Upload>
                    </Spin>
                </div>
            }
        },
        {
            title: '金融许可证',
            dataIndex: 'financialLicense',
            render:(text,record)=>{
                return <div className={styles.uploadAction}>
                    {
                        record.financialLicenseUrl ? 
                        <a onClick={()=>{
                            setPublicContent(record.financialLicenseUrl)
                            setContentVisible(true)
                          }} ><EyeOutlined /> </a>
                        :null

                    }
                    <Spin  style={{display:'inline-block'}} indicator={antIcon} spinning={uploadloading&&uploadType == 'financialLicense'&&record.id == info.id}>
                        <Upload  {...props}  onChange={(file)=>{handleUploadChange(file,record,'financialLicense')}} >
                            <a style={{whiteSpace:'nowrap'}}>{record.financialLicense ? '重新上传':'上传'}</a>
                        </Upload>
                    </Spin>
                </div>
            }
        },
    ];

    return (
        <div className={styles.uploadField}>
            <FileUpload
                ossEnum="BANK"
                multiple={true}
                max={1}
                href={
                    'https://ossonline.goodrs.cn/worker_supervision_oa/%E5%86%9C%E6%B0%91%E5%B7%A5%E5%B7%A5%E8%B5%84%E4%BF%9D%E8%AF%81%E9%87%91%E7%BC%B4%E5%AD%98%E9%87%91%E8%9E%8D%E6%9C%BA%E6%9E%84%E5%87%86%E5%85%A5%E6%83%85%E5%86%B5%E8%AF%B4%E6%98%8E%28%E6%A8%A1%E6%9D%BF%29%281%29.xlsx'
                }
                hrefText={'下载模版'}
                hrefTaget={'downloadFile'}
                actionUrl='/open/upload/resource'
                showUploadList={false}
                value={[]}
                type='.xlsx'
                text={tableList && tableList.length ? '重新上传' : '点击上传'}
                onChange={handleExcelUpload}
            />
            {
                tableList && tableList.length ? 
                <a onClick={()=>{setVisible(true)}} className={styles.preview}>查看上传内容</a>:
                null
            }
            <Modal
                title='文件上传'
                closable={true}
                onCancel={handleModalCancel}
                width={1200}
                visible={visible}
                okText='确认'
                cancelText='取消'
                onOk={handleSubmit}
                destroyOnClose={true}
            >
                <ProTable
                    rowKey="id"
                    dataSource={tableList}
                    columns={columns}
                    rowSelection={false}
                    options={false}
                    search={false}
                    pagination={false}
                    className={styles.table}
                /> 

            </Modal>
            {
                contentVisible ? 
                <Modal
                    visible={contentVisible}
                    footer={null}
                    onCancel={()=>{
                        setContentVisible(false)
                        setPublicContent('')
                    }}
                    width='800px'
                >
                    <iframe  src={publicContent}  style={{ width: "100%", height: "80vh", display:'block', margin:'0 auto' }} frameBorder="0"></iframe>
                </Modal>
                :null
            }
        </div>
    );
};

export default UploadFileList;
